import logging
import os
import threading
from logging.handlers import TimedRotatingFileHandler


class SingletonType(type):
    _instances = {}
    _lock = threading.Lock()  # 线程安全锁

    def __call__(cls, *args, **kwargs):
        with cls._lock:
            if cls not in cls._instances:
                instance = super().__call__(*args, **kwargs)
                cls._instances[cls] = instance
        return cls._instances[cls]


class Logger(metaclass=SingletonType):
    def __init__(self, name="AppLogger", log_dir="logs", level=logging.DEBUG):
        self.logger = logging.getLogger(name)
        self.logger.setLevel(level)

        if not os.path.exists(log_dir):
            os.makedirs(log_dir)

        log_file = os.path.join(log_dir, f"{name}.log")

        # 防止重复添加handler
        if not self.logger.hasHandlers():
            file_handler = TimedRotatingFileHandler(log_file, when="midnight", interval=1, backupCount=7,
                                                    encoding="utf-8")
            file_handler.suffix = "%Y-%m-%d.log"
            console_handler = logging.StreamHandler()

            formatter = logging.Formatter(
                fmt="%(asctime)s | %(levelname)s | %(filename)s:%(lineno)d | %(message)s",
                datefmt="%Y-%m-%d %H:%M:%S"
            )

            file_handler.setFormatter(formatter)
            console_handler.setFormatter(formatter)

            self.logger.addHandler(file_handler)
            self.logger.addHandler(console_handler)

    def debug(self, msg):
        self.logger.debug(msg)

    def info(self, msg):
        self.logger.info(msg)

    def warning(self, msg):
        self.logger.warning(msg)

    def error(self, msg):
        self.logger.error(msg)

    def critical(self, msg):
        self.logger.critical(msg)



